package com.lagou.demo.config;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;

public class LoginIntecepter implements HandlerInterceptor {
    private static final Logger logger = LogManager.getLogger(LoginIntecepter.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession();
        String s = request.getContextPath() + "/" + "index";
        if (session.getAttribute("sessionId")==null && request.getRequestURI().equals(s)) {
            logger.info("get it.....");
            String username = request.getParameter("username") == null ? "" : (String) request.getParameter("username");
            String pwd = request.getParameter("pwd") == null ? "" : (String) request.getParameter("pwd");
            if("admin".equals(username) && "admin".equals(pwd)){
                session.setAttribute("sessionId",session.getId());
                return true;
            }else{
                request.setAttribute("msg","请先登录");
                request.getRequestDispatcher("getLogin").forward(request,response);
                logger.info("用户账户或密码不对");
                return false;
            }
        }

        return true;
    }
}
